package role

import (
	"context"

	"mall/common/errorx"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/rpc/backendclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryMenuByRoleIdLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewQueryMenuByRoleIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryMenuByRoleIdLogic {
	return &QueryMenuByRoleIdLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *QueryMenuByRoleIdLogic) QueryMenuByRoleId(req *types.RoleMenuRequest) (resp *types.RoleMenuResponse, err error) {
	if req.Id == 0 {
		return nil, errorx.Error(errorx.ERROR_ROLE_ID_REQUIRED, "")
	}

	res, err := l.svcCtx.BackendRpc.MenuList(l.ctx, &backendclient.MenuListRequest{
		RoleId: req.Id,
		Status: 1,
	})
	if err != nil {
		return nil, err
	}

	var list []*types.RoleMenuItem
	if len(res.List) > 0 {
		for _, item := range res.List {
			list = append(list, &types.RoleMenuItem{
				Id:       item.Id,
				ParentId: item.ParentId,
				Title:    item.Name,
			})
		}
	}

	return &types.RoleMenuResponse{
		RoleId: req.Id,
		Menus:  list,
	}, nil
}
